package joymouse;

import java.awt.MouseInfo;
import java.awt.Point;
import net.java.games.input.Controller;

/**
 * Controller for the speed of the mouse cursor based on the joystick. This
 * input mode is easier to use and gives more precision.
 *
 * @author Ben Wolsieffer
 *
 */
public class RelativeMouseController extends MouseController {

    private long lastTime;
    // Used to reduce the signal so the mouse doesn't move to fast
    private static final double SPEED_MULTIPLIER = 0.000003;
    // Deadzone (disabled at the moment)
    private static final float DEAD_ZONE = 0.0f;

    /**
     * {@inheritDoc}
     */
    @Override
    protected void run() {
        // The current position of the mouse
        Point mousePos = MouseInfo.getPointerInfo().getLocation();
        int currX = mousePos.x;
        int currY = mousePos.y;
        long currTime = System.nanoTime();
        long elapsedTime = currTime - lastTime;
        //System.out.println(elapsedTime);
        float xData = xAxis.getPollData();
        float yData = yAxis.getPollData();
        int newX;
        if (xData < -DEAD_ZONE || xData > DEAD_ZONE) {
            newX = (int) ((double)xData * SPEED_MULTIPLIER * elapsedTime) + currX;
        } else {
            newX = currX;
        }
        int newY;
        if (yData < -DEAD_ZONE || yData > DEAD_ZONE) {
            newY = (int) ((double)yData * SPEED_MULTIPLIER * elapsedTime) + currY;
        } else {
            newY = currY;
        }
        // Checks to see if new position is not the old position so the mouse
        // isn't taken over by this program
        if (newX != currX || newY != currY) {
            robot.mouseMove(newX, newY);
        }
        lastTime = currTime;
    }

    /**
     * Assigns the specified {@link Controller} (ie. joystick) to be this device
     * controller's controller.
     *
     * @param cont The controller to use
     */
    public RelativeMouseController(Controller cont) {
        super(cont);
        lastTime = System.nanoTime();
    }
}
